package controllers.facebook;


import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.JsonNode;

import play.Logger;
import play.Play;
import play.libs.Json;
import play.mvc.Controller;
import scala.actors.threadpool.Arrays;

/**
 *
 * @author Eric Jacob
 */
public class FacebookManager extends Controller{

	private static String appId = Play.application().configuration().getString("vvins.fb.appId");
    private static String appSecret = Play.application().configuration().getString("vvins.fb.appSecret");

	
    public static String getCookieName(){
    	return "fbsr_" + getAppId();
    }
    
    public static Map<String, Object> parseCookie(String value) {
    		Map<String,Object> result = new HashMap<String,Object>();
    		String[] splits = value.split(Pattern.quote("."));
			byte[] encodedSig = splits[0].getBytes();
			byte[] sig = base64UrlDecode(encodedSig);
			byte[] encodedData = splits[1].getBytes();
			JsonNode data = (JsonNode)  Json.parse(new String(base64UrlDecode(encodedData)));
			result.put("encodedSig",encodedSig);
			result.put("sig",sig);
			result.put("encodedData",encodedData);
			result.put("data",data);
			return result;
    }
    
    

    public static String getAccessToken(String cookie) {
        Map<String,Object> results = parseCookie(cookie);
        JsonNode data = (JsonNode)results.get("data");
        String algorithm = data.get("algorithm").getTextValue();
        if ("HMAC-SHA256".equals(algorithm)) {
            try {
                SecretKeySpec key = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256");
                Mac hmac = Mac.getInstance("HMACSHA256");
                hmac.init(key);
                byte[] expectedSig = hmac.doFinal((byte[])results.get("encodedData"));
                byte[] sig = (byte[])results.get("sig");
                if (Arrays.equals(sig,expectedSig)) {
                    return data.get("code").getTextValue();
                }
                
            } catch (Exception ex) {
            	Logger.error(ex.getMessage());
            }
        }
        return null;
    }


    private static byte[] base64UrlDecode(byte[] encoded) {
    	Base64 b = new Base64(true);
    	return Base64.decodeBase64(encoded);
    }



	public static String getAppId() {
		return appId;
	}



	public static void setAppId(String appId) {
		FacebookManager.appId = appId;
	}



	public static String getAppSecret() {
		return appSecret;
	}



	public static void setAppSecret(String appSecret) {
		FacebookManager.appSecret = appSecret;
	}
}
